<?php


namespace App\Elastic;


use Carbon\Carbon;
use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;

class Articles extends EsModel
{
    const INDEX = 'articles';

    public static function getIndex(): string
    {
        return sprintf('%s%s%s', 'demo_', self::INDEX, time());
    }

    public static function getAlias(): string
    {
        return self::INDEX;
    }

    public static function getMapping(): array
    {
        return include(__DIR__ . '/mappings/articles.php');
    }


    public function pushToIndex($mixed)
    {
        $params = [];
        $spider_at = date('Y-m-d H:i:s');
        foreach ($mixed as $item) {
            $params['body'][] = [
                'index' => [
                    '_index' => static::getAlias(),
                    '_type' => '_doc',
                    '_id' => $item['node']['id']
                ]
            ];
            $item['node']['createdAt'] = Carbon::parse($item['node']['createdAt'])->tz('UTC')->toDateTimeString();
            $item['node']['updatedAt'] = Carbon::parse($item['node']['updatedAt'])->tz('UTC')->toDateTimeString();
            $item['node']['spiderAt'] = $spider_at;
            $params['body'][] = $item['node'];
        }
        return $this->client->bulk($params);
    }

    public static function getSetting(): array
    {
        return [
            'number_of_shards' => 3,
            'number_of_replicas' => 1
        ];
    }

    public static function rebuild(): string
    {
        // TODO: Implement rebuild() method.
    }

    public function search()
    {
        $result = $this->client->search([
            'index' => static::getAlias(),
            'body' => []
        ]);
        dd($result);
    }
}